package com.easydict.resolver;

import com.easydict.spi.DictionaryResolutionContext;
import com.easydict.spi.DictionaryResolver;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * 组合解析器：按子解析器优先级依次尝试
 */
public class CompositeDictionaryResolver implements DictionaryResolver {

    private final List<DictionaryResolver> resolvers;

    public CompositeDictionaryResolver(DictionaryResolver... resolvers) {
        this.resolvers = Arrays.asList(resolvers);
        this.resolvers.sort(Comparator.comparingInt(DictionaryResolver::getPriority));
    }

    @Override
    public Optional<String> resolve(DictionaryResolutionContext context) {
        for (DictionaryResolver r : resolvers) {
            if (r.supports(context)) {
                Optional<String> rs = r.resolve(context);
                if (rs.isPresent()) {
                    return rs;
                }
            }
        }
        return Optional.empty();
    }

    @Override
    public int getPriority() {
        return 0;
    }

    @Override
    public boolean supports(DictionaryResolutionContext context) {
        return true;
    }

    @Override
    public String getName() {
        return "CompositeDictionaryResolver";
    }
}


